package com.ssyshop.info.activity.entry;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.ssyshop.info.R;
import com.ssyshop.info.activity.MainActivity;
import com.ssyshop.info.utils.Config;
import com.ssyshop.info.utils.UpdateApplication;
import com.ssyshop.info.view.SelfDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.yanzhenjie.permission.SettingService;

import java.util.List;

public class LoadActivity extends AppCompatActivity {

    /**
     * 让引导页只出现一次的方法
     */
    private SharedPreferences preferences;
    private int count;
    private SelfDialog selfDialog;
    private MyReceiver receiver;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0x111) {

                if (count == 0) {
                    // 进入引导页
                    startActivity(new Intent(LoadActivity.this, GuideActivity.class));
                } else {
                    // 进入首页
                    startActivity(new Intent(LoadActivity.this, MainActivity.class));
                }
                SharedPreferences.Editor editor = preferences.edit();
                editor.putInt("count", ++count);
                editor.commit();
                finish();
            }

        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除actionbar
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        // 设置状态栏透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_load);

        preferences = getSharedPreferences("count", Context.MODE_PRIVATE);
        count = preferences.getInt("count", 0);
        //动态注册广播
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Config.BROADCAST_LOAD);
        registerReceiver(receiver, filter);

        //设置闪屏显示的图片


        checkNetwork();
    }


    private static final int REQUEST_CODE_PERMISSION_LOCATION = 100;
    private static final int REQUEST_CODE_SETTING = 300;

    // 检查网络
    private void checkNetwork() {

        ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cwjManager.getActiveNetworkInfo();
        // 存在网络
        if (info != null && info.isAvailable()) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 适配版本在6.0以上
                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    // Toast.makeText(LoadActivity.this, "读写内存授权已存在", Toast.LENGTH_SHORT).show();
                    //检查更新
                    CheckVerTask task = new CheckVerTask();
                    task.execute();
                } else {
                    //  Toast.makeText(LoadActivity.this, "申请读写内存授权", Toast.LENGTH_SHORT).show();
                    AndPermission.with(LoadActivity.this)
                            .requestCode(REQUEST_CODE_PERMISSION_LOCATION)
                            .permission(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .callback(permissionListener)
                            // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                            // 这样避免用户勾选不再提示，导致以后无法申请权限。
                            // 你也可以不设置。
                            .rationale(rationaleListener)
                            .start();
                }
            } else {// 适配版本在6.0以下
                //检查更新
                CheckVerTask task = new CheckVerTask();
                task.execute();
            }

        } else {// 没有网络
            selfDialog = new SelfDialog(this, 1);//默认为0,  1：只有一个按钮
            selfDialog.setTitle("系统提示");
            selfDialog.setMessage("网络连接失败，请检查。");
            selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    selfDialog.dismiss();
                    System.exit(0);
                }
            });
            selfDialog.show();
        }

    }


    /**
     * 权限申请回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        // 权限申请成功回调。
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == REQUEST_CODE_PERMISSION_LOCATION) {
                // Toast.makeText(LoadActivity.this, "读写内存授权成功", Toast.LENGTH_SHORT).show();
                //检查更新
                CheckVerTask task = new CheckVerTask();
                task.execute();
            }
        }

        // 权限申请失败回调。
        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == REQUEST_CODE_PERMISSION_LOCATION) {
                // Toast.makeText(LoadActivity.this, "读写内存授权失败", Toast.LENGTH_SHORT).show();
            }

            final SettingService settingHandle = AndPermission.defineSettingDialog(LoadActivity.this, REQUEST_CODE_SETTING);
            selfDialog = new SelfDialog(LoadActivity.this, 0);//默认为0,  1：只有一个按钮
            selfDialog.setTitle("系统提示");
            selfDialog.setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！");
            selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    settingHandle.execute();
                }
            });
            selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    selfDialog.dismiss();
                    //settingHandle.cancel();
                    System.exit(0);
                }
            });
            selfDialog.show();

            // 用户是否有勾选不再提示并拒绝的权限。
//            if (AndPermission.hasAlwaysDeniedPermission(LoadActivity.this, deniedPermissions)) {
            // 第一种：用默认的提示语。
//                AndPermission.defaultSettingDialog(LoadActivity.this, REQUEST_CODE_SETTING).show();

            // 第二种：用自定义的提示语。
//             AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
//                     .setTitle("权限申请失败")
//                     .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
//                     .setPositiveButton("好，去设置")
//                     .show();

            //            第三种：自定义dialog样式。
//            SettingService settingHandle = AndPermission.defineSettingDialog(LoadActivity.this, REQUEST_CODE_SETTING);
//            你的dialog点击了确定调用：
//            settingHandle.execute();
//            你的dialog点击了取消调用：
//            settingHandle.cancel();
//            }
        }
    };

    /**
     * Rationale功能是在用户拒绝一次权限后，再次申请时检测到已经申请过一次该权限了，
     * 允许开发者弹窗说明申请权限的目的，获取用户的同意后再申请权限，避免用户勾选不再提示，导致不能再次申请权限。
     */
    private RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
            // 这里用AndPermission默认对话框：
            AndPermission.rationaleDialog(LoadActivity.this, rationale).show();
            // 此对话框可以自定义，调用rationale.resume()就可以继续申请。 rationale.cancel();不继续申请
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SETTING) {
            // 你可以在这里检查你需要的权限是否被允许，并做相应的操作。
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                //检查更新
                CheckVerTask task = new CheckVerTask();
                task.execute();
            } else {
                Toast.makeText(LoadActivity.this, "读写内存授权失败,系统功能无法实现，退出程序", Toast.LENGTH_SHORT).show();
                System.exit(-1);
            }
        }
    }

    /**
     * 检查版本更新
     *
     * @author xwc
     */
    private class CheckVerTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            if (UpdateApplication.getUpdateInfo(LoadActivity.this)) {
                // 有最新版本
                return true;
            } else {
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean flag) {

            if (flag) {//有最新版本
                UpdateApplication.newUpdate(LoadActivity.this);
            } else {
                handler.sendEmptyMessage(0x111);
            }

        }
    }


    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            handler.sendEmptyMessage(0x111);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
